<template>
  <view class="article-details-page">
    <!-- 头部导航栏 -->
    <nav-bar title="文章详情" textAlign="center" @load="handleLoadNav"></nav-bar>
    <scroll-view scroll-y="true" class="scroll-view-container" :style="{'height':viewHeight+'px'}"
      v-if="articleContent&&articleContent.articleId">
      <view class="article-details-container">
        <!-- 文章详情区域 -->
        <view class="article-content-container">
          <!-- 用户信息部分-->
          <view class="head-container">
            <view class="user-info" @click="handleJumpPage(articleContent.user.userId)">
              <image class="user-avatar" :src="articleContent.user.avatar"></image>
              <!-- 用户昵称与发布时间 -->
              <view class="user-name-and-date">
                <view class="user-name">
                  {{articleContent.user.userName}}
                </view>
                <!-- 名：引出 /plugins/plugins.js  -->
                <view class="date">{{articleContent.article.createTime|formatDate( 'yyyy年MM月dd日 hh:mm')}}发布</view>
              </view>
            </view>
            <!-- 关注状态 -->
            <block v-if="userId !== articleContent.user.userId">
              <view v-if="articleContent.fansState&&!articleContent.followState" class="follow-on"
                @click="handleAttention">已关注</view>
              <view v-else-if="articleContent.fansState&&articleContent.followState" class="follow-on"
                @click="handleAttention">互相关注</view>
              <view v-else class="follow-off" @click="handleAttention"> +关注 </view>
            </block>
          </view>


          <!-- 文章标题部分 -->
          <view class="title-container">
            {{articleContent.article.title}}
          </view>
          <!-- 文章内容部分 -->
          <view class="content-container">
            <text selectable>
              {{articleContent.article.content}}
            </text>
            <view class="image-container" v-for="(item,index) in articleImageList" :key="index">
              <image :src="item" mode="widthFix"></image>
            </view>
          </view>
          <!-- 互动部分 -->
          <view class="bottom-container">
            <view>
              <!-- 转发 -->
              <view>
                <!-- 名：条件编译兼容转发事件 -->
                <!-- #ifdef  MP-WEIXIN -->
                <button class="share-btn" open-type="share" type="primary">
                  <uni-icons class="icon" :color="'#a2a2a2'" custom-prefix="iconfont" type="icon-forward"
                    size="36rpx"></uni-icons>
                  <text>{{articleContent.article.shareNum}}</text>
                </button>
                <!-- #endif -->
                <!-- #ifdef  H5 -->
                <button class="share-btn" @click="handleH5Share">
                  <uni-icons class="icon" :color="'#a2a2a2'" custom-prefix="iconfont" type="icon-forward" size="36rpx">
                  </uni-icons>
                  <text>{{articleContent.article.shareNum}}</text>
                </button>
                <!-- #endif -->
              </view>
              <!-- 评论 -->
              <view>
                <uni-icons class="icon" :color="'#a2a2a2'" custom-prefix="iconfont" type="icon-comment" size="36rpx">
                </uni-icons>
                <text>{{commentNum}}</text>
              </view>
              <!-- 点赞 -->
              <view @click="handleLikeArticle">
                <uni-icons class="icon" custom-prefix="iconfont" type="icon-like"
                  :color="articleContent.likeStatus?'#3fd3d1':'#a2a2a2'" size="36rpx">
                </uni-icons>
                <text>{{articleContent.article.likeNum}}</text>
              </view>
            </view>
          </view>

        </view>
        <!-- 评论 -->
        <common-comments :creatorUserId="articleContent.user.userId" :currentUserId="userId"
          :loadMainCommentData="handleGetMainCommentList" :loadChildCommentData="handleGetChildCommentList"
          :removeCommentData="handleRemoveCommentData" :sendCommentData="handleSendCommentData"
          :likeComment="handleLikeComment" :commentNum="commentNum" :props="commenProps">
        </common-comments>
      </view>
    </scroll-view>
    <view class="data-empty" v-if="emptyData">
      <view class="empty__image">
        <image src="/static/empty.png"></image>
      </view>
      <text class="empty__description">文章不存在</text>

    </view>
  </view>
</template>

<script>
  // 名：为了防止ios下拉出现白屏的问题，采用设置页面 disableScroll为true，页面中使用 scroll-view 组件
  import {
    // 文章相关
    getArticleContentApi,
    postArticleThumbsUpApi,
    postreplyThumbsUpApi,
    postUserFollowApi,
    // 评论相关
    getComment,
    postSendCommentApi,
    deleteReplyApi,
    // 转发
    addShare
  } from '@/api/community/article-details.js'


  export default {
    data() {
      return {
        // 文章ID
        articleId: '',
        // 文章信息
        articleContent: {},
        // 当前用户id
        userId: '',
        // 视图高度
        viewHeight: 0,
        // 评论数
        commentNum: 0,
        // 配置
        commenProps: {
          content: 'content',
          avatar: "avatar",
          commentId: "commentId",
          commentsNum: "commentsNum",
          content: "content",
          createTime: "createTime",
          likeNum: 'likeNum',
          likeStatus: "status",
          userId: "userId",
          userName: "userName",
          wasRepliedName: 'wasRepliedName',
        },
        emptyData: false
      };
    },
    onShow() {
      getApp().globalData.getUser()
      if (getApp().globalData.login) {
        this.userId = getApp().globalData.getUser().userId
        this.handleGetArticleContent(this.articleId)
      } else {
        uni.switchTab({
          url: "/pages/my/my"
        })
      }
    },
    onLoad(e) {
      this.articleId = e.id;
      this.not2User = e.not2User;
      // 已登录获取文章数据 未登录返回我的页面

    },
    computed: {
      // 文章图片列表
      articleImageList() {
        let imageLink = this.articleContent && this.articleContent.image && this.articleContent.image.imageLink ? this
          .articleContent
          .image.imageLink : "";
        // 因为获取的文章数据中，文章图片信息是以 “;” 符号分割的字符串，需要通过split将字符串转为数组。
        return imageLink.split(';')
      }
    },
    // 设置分享信息 
    onShareAppMessage() {
      this.handleAddShare();
      return {
        title: this.articleContent.title,
        path: `/pages/community/article-details/article-details?id=${this.articleId}`,
        imageUrl: `${this.articleImageList[0]?this.articleImageList[0]:'/static/logo/logo.png'}`
      }
    },
    onShareTimeline() {},
    methods: {

      // ------------------------------------------
      // 任务十中可删除
      handleLoadNav({
        height,
        navHeight
      }) {
        // 可移动视图的高度 = 视图高度 - 导航栏高度
        this.viewHeight = height - navHeight;
      },
      // ---------------------------------------------------------------------- 文章
      // 获取文章数据
      async handleGetArticleContent() {
        uni.showLoading();
        const {
          data: res
        } = await getArticleContentApi(this.articleId)
        if (res.success) {
          this.$set(this, 'articleContent', res.data.detail)
        } else {
          this.emptyData = true;
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
        uni.hideLoading();
      },
      // 关注文章发布者
      // 暂时不讲 []
      handleAttention() {
        let userId = this.articleContent.user.userId
        // this.articleContent.fansState为true表示已关注 为false表示未关注
        if (this.articleContent.fansState == true) {
          uni.showModal({
            title: '提示',
            content: '是否取消关注',
            success: (res) => {
              if (res.confirm) {
                postUserFollowApi(userId).then((res) => {
                  this.articleContent.fansState = !this.articleContent.fansState
                })
              }
            }
          });
        } else {
          postUserFollowApi(userId).then((res) => {
            this.articleContent.fansState = !this.articleContent.fansState
          })
        }
      },
      // 文章点赞
      async handleLikeArticle() {
        let {
          data: res
        } = await postArticleThumbsUpApi(this.articleId)
        if (res.success) {
          this.articleContent.likeStatus = !this.articleContent.likeStatus;
          if (this.articleContent.likeStatus) {
            this.articleContent.article.likeNum++
          } else {
            this.articleContent.article.likeNum--
          }
        }
        this.handleUpdateData();
      },
      // h5端转发事件
      handleH5Share() {
        // h5 浏览器 采用展示遮罩层提示分享
        // h5 微信浏览器 可调用js-sdk进行分享 采用 https://ask.dcloud.net.cn/article/35380
      },
      // 增加转发数
      handleAddShare() {
        addShare(this.articleId)
        this.articleContent.article.shareNum++;
        this.handleUpdateData();
      },
      // 跳转到用户界面
      // 任务十暂时不讲 []
      handleJumpPage(uid) {
        if (this.not2User == 'true') {
          return;
        }
        uni.navigateTo({
          url: `/pages/my/userInfo/userInfo?id=${uid}`
        });
      },
      // ---------------------------------------------------------------------------- 评论
      // 加载主评论列表
      async handleGetMainCommentList(data) {
        const {
          data: res
        } = await getComment(this.articleId, data.page)
        this.commentNum = res.data.list.total;
        this.handleUpdateData()
        return {
          pages: res.data.list.pages,
          data: res.data.list.records,
          success: res.success
        }
      },
      // 加载子评论列表
      async handleGetChildCommentList(data) {
        const {
          data: res
        } = await getComment(this.articleId, data.page, data.ext.commentId)
        return {
          pages: res.data.list.pages,
          data: res.data.list.records,
          success: res.success
        }
      },
      // 删除评论
      async handleRemoveCommentData(data) {
        let {
          data: res
        } = await deleteReplyApi(data.commentId);
        res.success && this.commentNum--
        this.handleUpdateData()
        return {
          success: res.success
        }
      },
      // 发布评论
      async handleSendCommentData(data) {
        let type = data.type;
        let content = data.content;
        let args = [];
        if (type == 0) {
          // 默认评论参数
          args = [content, this.articleId];
        } else {
          let commentId = data.data.commentId;
          // 回复评论参数
          args = [content, this.articleId, commentId];
        }
        let {
          data: res
        } = await postSendCommentApi(...args);
        res.success && this.commentNum++
        this.handleUpdateData()
        return {
          success: res.success,
          data: res.data.comment,
          message: res.message,
        }
      },
      // 点赞评论
      async handleLikeComment(data) {
        let commentId = data.commentId;
        let status = data.status;
        let likeNum = data.likeNum;
        let {
          data: res
        } = await postreplyThumbsUpApi(commentId);
        !status ? likeNum++ : likeNum--;
        return {
          success: res.success,
          status: !status,
          likeNum: likeNum
        }
      },
      handleUpdateData() {
        this.$nextTick(() => {
          uni.$emit('article-update', {
            data: {
              article: {
                likeNum: this.articleContent.article.likeNum,
                shareNum: this.articleContent.article.shareNum,
                commentNum: this.articleContent.article.commentNum
              }
            },
            value: this.articleId,
            type: "article-update"
          })
        })

      }
    }
  }
</script>

<style lang="scss" scoped>
  .article-details-page {
    background-color: #fff;
    width: 100%;
    height: 100vh;
    overflow: hidden;

    // 可滚动区域
    .scroll-view-container {
      .loading-container {
        width: 100%;
      }

      .article-details-container {
        width: 100%;

        .article-content-container {
          background-color: #ffffff;
          border-bottom: 2rpx solid #EEF2F4;
          padding: 40rpx;

          .head-container {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .user-info {
              display: flex;

              .user-avatar {
                width: 80rpx;
                height: 80rpx;
                border-radius: 50%;
                margin-right: 12rpx;
                box-shadow: 0 0 4rpx 0 rgba(0, 0, 0, 0.1);
              }

              .user-name-and-date {
                .user-name {
                  font-size: 32rpx;
                  font-weight: 500;
                }

                .date {
                  color: #7A7A7A;
                  font-size: 24rpx;
                  font-weight: 400;
                }
              }
            }



            .follow-off {
              width: 124rpx;
              height: 52rpx;
              background-color: #3FD3D1;
              border-radius: 56rpx;
              font-size: 28rpx;
              color: #ffffff;
              text-align: center;
              line-height: 52rpx;
            }

            .follow-on {
              height: 52rpx;
              // background-colo: #C0C0C0;
              border-radius: 56rpx;
              font-size: 24rpx;
              // color: #FFFFFF;
              text-align: center;
              line-height: 52rpx;
              padding: 0 16rpx;
              border: 1px solid rgba(102, 102, 102, 0.4);
            }
          }

          .title-container {
            font-size: 32rpx;
            font-weight: 700;
            margin: 30rpx 0 0 0;
            word-break: break-word;
            text-overflow: ellipsis;
          }

          .content-container {
            margin-top: 10rpx;

            text {
              word-break: break-word;
              font-size: 28rpx;
              font-weight: 400;
              color: #333333;
            }

            .image-container {
              text-align: center;

              image {
                margin-top: 20rpx;
                border-radius: 30rpx;
                width: 100%;
                min-height: 320rpx;
                background-color: #e8ebed;
              }
            }
          }

          .bottom-container {
            width: 100%;
            height: 48rpx;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 20rpx;

            >view {
              width: 400rpx;
              height: 48rpx;
              display: flex;
              justify-content: space-between;
              align-items: center;

              view {
                width: 120rpx;
                height: 88rpx;
                display: flex;
                align-items: center;

                image {
                  width: 36rpx;
                  height: 36rpx;
                }

                button::after {
                  outline: none;
                  border: none;
                }

                text,
                .view {
                  color: #7A7A7A;
                  font-size: 28rpx;
                  background-color: #FFFFFF;
                  padding-left: 16rpx;
                  text-align: center;
                }

                .share-btn {
                  width: 100%;
                  height: 100%;
                  background-color: #FFFFFF;
                  display: flex;
                  align-items: center;
                  padding: 0 !important;

                  text {
                    color: #7A7A7A;
                    font-size: 28rpx;
                    padding-left: 16rpx;
                    background-color: #FFFFFF;
                  }
                }

                .share-btn::after {
                  display: none;
                }
              }
            }
          }

        }

      }

    }

    // 列表数据为空时展示容器
    .data-empty {
      box-sizing: border-box;
      padding: 64px 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .empty__image {
        width: 320rpx;
        height: 320rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .empty__description {
        padding: 0 120rpx;
        color: #969799;
        font-size: 28rpx;
        line-height: 40rpx;
      }


    }

  }
</style>